package demo4.mapper;

import com.alibaba.druid.pool.DruidDataSource;
import demo4.config.DBUtil;
import demo4.vo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Component
public class UserMapper implements IUserMapper{
    @Autowired
    private DruidDataSource dataSource;//依赖连接池，希望将Spring容器将连接池注入到该对象中；
    @Override
    public int insert(User user) {
        try (Connection connection=dataSource.getConnection()){
            String sql="INSERT INTO user(username,password,nickname,age) " +
                    "VALUES(?,?,?,?)";
            PreparedStatement ps=connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            ps.setString(3,user.getNickname());
            ps.setInt(4,user.getAge());
            return ps.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public User selectByUsername(String username) {
        try (Connection connection= dataSource.getConnection();){
           String sql="SELECT id,username,password,nickname,age " +
                   "FROM user " +
                   "WHERE username=?";
            PreparedStatement ps=connection.prepareStatement(sql);
            ps.setString(1,username);
            ResultSet rs=ps.executeQuery();
            if (rs.next()){
                User user=new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setNickname(rs.getString("nickname"));
                user.setAge(rs.getInt("age"));
                return user;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
